package com.lwm.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lwm.domain.ResponseResult;
import com.lwm.domain.SalesOrder;
import com.lwm.dto.PageParams;
import com.lwm.dto.SalesOrderDto;
import com.lwm.mapper.SalesOrderMapper;
import com.lwm.service.SalesOrderService;
import com.lwm.utils.Code;
import com.lwm.utils.HintMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SalesOrderServiceImpl implements SalesOrderService {
    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Override
    public SalesOrder getById(Long id) {
        return salesOrderMapper.getById(id);
    }

    @Override
    public ResponseResult<Object> getPage(SalesOrderDto salesOrderDto) {
        Integer page = salesOrderDto.getPage();
        if(salesOrderDto.getSize() == null) salesOrderDto.setSize(10);
        if(page == null) page = 1;
        // 拿到总条数
        Long total = salesOrderMapper.getTotal(salesOrderDto);
        // 拿到最大页码
        Double maxPage = Math.ceil(Double.valueOf(total) / Double.valueOf(salesOrderDto.getSize()));
        // 求当前页码
        Integer currentPage = maxPage.intValue() < page ? maxPage.intValue() : page;
        System.out.println(currentPage);
        currentPage = currentPage <= 0 ? 1 : currentPage;
        // 求开始的页码
        Integer startPage = (currentPage - 1) * salesOrderDto.getSize();
        salesOrderDto.setPage(startPage);
        List<SalesOrder> pageList = salesOrderMapper.getPage(salesOrderDto);
        PageParams<Object> objectPageParams = new PageParams<Object>(currentPage, salesOrderDto.getSize(), total.intValue(), pageList);

        return new ResponseResult(Code.GET_OK, HintMessage.GET_OK_HINT, objectPageParams);
    }

    @Override
    public ResponseResult<Object> getAll() {
        List<SalesOrder> all = salesOrderMapper.getAll();
        return new ResponseResult(Code.GET_OK, HintMessage.GET_OK_HINT, all);
    }

    @Override
    public ResponseResult<Object> insert(SalesOrder salesOrder) {
        if(salesOrder.getIsDeleted() == null) salesOrder.setIsDeleted(0);
        salesOrder.setId(IdUtil.getSnowflakeNextId());
        System.out.println(salesOrder);
        salesOrderMapper.insert(salesOrder);

        return new ResponseResult(Code.SAVE_OK, HintMessage.SAVE_OK_HINT);
    }

    @Override
    public ResponseResult<Object> updateById(SalesOrder salesOrder) {
        salesOrderMapper.update(salesOrder);
        return new ResponseResult<>(Code.UPDATE_ERR, HintMessage.EDIT_OK_HINT);
    }

    @Override
    public ResponseResult<Object> removeBatch(List<Long> id) {
        salesOrderMapper.removeBatch(id);
        return new ResponseResult<>(Code.DELETE_OK, HintMessage.REMOVE_OK_HINT);
    }

}
